import unittest
from typing import List


class Solution:

    def compress(self, chars: List[str]) -> int:

        # anchor指向当前分组的起始位置
        anchor = write = 0

        for read, c in enumerate(chars):

            # 如果到了数组末尾或者当前字符与后一个字符不同,表示遇到新分组
            if read + 1 == len(chars) or chars[read + 1] != c:

                # 将当前分组的第一个字符写到write的位置
                chars[write] = chars[anchor]
                write += 1

                # 如果分组长度大于1,将长度转换成字符串并写入
                if read > anchor:
                    for digit in str(read - anchor + 1):
                        chars[write] = digit
                        write += 1

                # 将anchor移到下一分组的起始位置
                anchor = read + 1

        # 返回处理后的数组长度
        return write


class TestSolution(unittest.TestCase):

    def test_empty(self):
        chars = []
        expected = 0
        sol = Solution()
        self.assertEqual(expected, sol.compress(chars))

    def test_single_char(self):
        chars = ["a"]
        expected = 1
        sol = Solution()
        self.assertEqual(expected, sol.compress(chars))

    def test_same_chars(self):
        chars = ["a","a","a","a","a"]
        expected = 2
        sol = Solution()
        self.assertEqual(expected, sol.compress(chars))

    def test_different_chars(self):
        chars = ["a","b","c","d","e"]
        expected = 5
        sol = Solution()
        self.assertEqual(expected, sol.compress(chars))


if __name__ == '__main__':
    unittest.main()